import java.awt.Graphics2D
import java.awt.geom.AffineTransform
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import java.awt.Graphics
import java.awt.Image

includeTargets << new File("${grailsHome}/scripts/Init.groovy")
includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")
includeTargets << new File("scripts/RenderAssets.groovy")

target(renderFilmStrip:"Compiles multiple images into one film strip"){
	depends(renderAssets, classpath)
	try{
		println("Rendering film strip...")
		def target = 'web-app/images/';
		def targetDir = new File("${target}");
				
		targetDir.eachFile{ file ->
			if( !file.directory ) return
			
			compilePngAnimationStrip(file)
		}
	}catch(Exception e){
		e.printStackTrace();
	}
}

setDefaultTarget( renderFilmStrip );

def loadImage(imageSrc){
	return ImageIO.read(imageSrc);
}

def scale(BufferedImage bImage, int scaleX, int scaleY ){
    def scaledImage = bImage.getScaledInstance(scaleX,scaleY,Image.SCALE_AREA_AVERAGING);
    BufferedImage temporaryImage = new BufferedImage(scaleX, scaleY, bImage.getType());
    Graphics g = temporaryImage.getGraphics()
    g.drawImage(scaledImage, 0, 0, null)
    g.dispose()
    return temporaryImage;
}

def compilePngAnimationStrip(dir){
	
	def imageMap = [:];
	dir.eachFileRecurse {
		if( it.directory ) return;
		if( it.parentFile.name.lastIndexOf('_') == it.parentFile.name.indexOf('_') ) return;
		
		if( it.parentFile == dir ) return;
				
		def name = it.parentFile.name
		
		def image = loadImage( it )
		def actName = name[ name.lastIndexOf('_') .. -1]
		def imageName = it.parentFile.parentFile.name
						
		//if( imageName.lastIndexOf('_') < 0 ) return;
		//imageName = imageName[ 0 .. imageName.lastIndexOf('_')-1]
				
		if(!imageMap[imageName + actName]){
			imageMap[imageName + actName] = [height: image.getHeight(null), width: image.getWidth(null), images: [] ]
		}
		imageMap[imageName + actName].images.push( image );
	}

	imageMap.each {
		def imageMeta = it.value
		def width = imageMeta.width
		def height = imageMeta.height
		def images = imageMeta.images
		
		BufferedImage bufferedImage = new BufferedImage( width * images.size(), height, BufferedImage.TYPE_INT_ARGB );
		
		Graphics2D g2d = bufferedImage.createGraphics();
		
		AffineTransform at = new AffineTransform();
		at.translate((width*images.size())-width, 0);
			
		images.each {
			g2d.drawImage( it, at, null)
			at.translate(-width, 0);
		}
		
		g2d.dispose()
		
		def PATH_SEP = File.separator
		
		if( height != 100 ){
			println("Resizing... ${height}")
            bufferedImage = scale(bufferedImage, 100 * images.size(), 100);
		}
		println("Writing to " +dir.absolutePath+PATH_SEP+ it.key);
		ImageIO.write(bufferedImage, "png", new File(dir.absolutePath + PATH_SEP + it.key + ".png"));
	}
}
